package com.kkb.springmvc.servlet;

import com.kkb.springmvc.adapter.HandlerAdapter;
import com.kkb.springmvc.adapter.HttpRequestHandlerAdapter;
import com.kkb.springmvc.adapter.SimpleControllerHandlerAdapter;
import com.kkb.springmvc.mapping.BeanNameUrlHandlerMapping;
import com.kkb.springmvc.mapping.HandlerMapping;
import com.kkb.springmvc.mapping.SimpleUrlHandlerMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 分发类
 */
public abstract class DispatcherServlet extends AbstractServlet {

    private List<HandlerAdapter> handlerAdapters = new ArrayList();
    private List<HandlerMapping> handlerMappings = new ArrayList();

    @Override
    public void init() throws ServletException {
        handlerAdapters.add(new HttpRequestHandlerAdapter());
        handlerAdapters.add(new SimpleControllerHandlerAdapter());

        handlerMappings.add(new BeanNameUrlHandlerMapping());
        handlerMappings.add(new SimpleUrlHandlerMapping());

    }

    /**
     * 请求分发
     *
     * @param request
     * @param response
     */
    @Override
    public void doDispatch(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 根据请求找到对应的处理类
            Object handler = getHandler(request);
            if (handler == null) {
                return;
            }
            // 调用处理类的方法，执行请求，并返回处理结果
            HandlerAdapter handlerAdapter = getHandlerAdapter(handler);
            handlerAdapter.handleRequest(handler, request, response);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private HandlerAdapter getHandlerAdapter(Object handler) {
        if (handlerAdapters != null) {
            for (HandlerAdapter ha : handlerAdapters) {
                if (ha.supports(handler)) {
                    return ha;
                }
            }
        }
        return null;
    }

    private Object getHandler(HttpServletRequest request) throws Exception {
        if (handlerMappings != null) {
            for (HandlerMapping hm : handlerMappings) {
                Object handler = hm.getHandler(request);
                if (handler != null) {
                    return handler;
                }
            }
        }
        return null;
    }
}
